package com.example.customer01.service.impl;

import com.example.customer01.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.access.path}")
    private String accessPath;

    @Override
    public String uploadFile(MultipartFile file, String directory) {
        try {
            // 创建目录
            String dirPath = uploadPath + "/" + directory;
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件，自动关闭流
            Path filePath = Paths.get(dirPath, filename);
            try (InputStream in = file.getInputStream()) {
                Files.copy(in, filePath);
            }

            // 返回访问URL
            return accessPath + "/" + directory + "/" + filename;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Override
    public void deleteFile(String fileUrl) {
        try {
            String filePath = fileUrl.replace(accessPath, uploadPath);
            Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            throw new RuntimeException("文件删除失败", e);
        }
    }
} 